package com.xxg.renrenuser.service;

import com.xxg.renrencommon.domain.result.BaseResult;
import com.xxg.renrencommon.exception.exceptionenum.UserExceptionCodeCodeEnum;
import com.xxg.renrenuser.cache.CodeTableCache;
import com.xxg.renrenuser.dao.CodeTableDao;
import com.xxg.renrenuser.dao.bean.MyKeyValue;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 字典接口实现
 *
 * @author xxg
 * @date 2020/11/24
 */
@Service
@AllArgsConstructor
public class DictionaryServiceImpl implements DictionaryService {
    private final CodeTableDao codeTableDao;
    private final CodeTableCache codeTableCache;

    @Override
    public BaseResult updateCodeTable(String tableName, String keyValues) {
        // 解析键值对
        String[] rows = keyValues.split(";");
        List<MyKeyValue> myKeyValues = new ArrayList<>(rows.length);
        Set<String> keySet = new HashSet<>(rows.length * 4 / 3 + 1);
        for (String row : rows) {
            String[] kv = row.split(":");
            if (!keySet.contains(kv[0])) {
                keySet.add(kv[0]);
                MyKeyValue keyValue = new MyKeyValue();
                keyValue.setKey(kv[0]);
                keyValue.setValue(kv[1]);
                myKeyValues.add(keyValue);
            }
        }
        if (!codeTableDao.hasTable(tableName)) {
            return new BaseResult(UserExceptionCodeCodeEnum.DICTIONARY_NOT_EXISTS, "", null);
        }
        codeTableDao.update(tableName, myKeyValues);
        // 更新缓存
        codeTableCache.updateCacheByTableName(tableName, myKeyValues);
        return new BaseResult();
    }

    @Override
    public BaseResult getCodeTable(String tableName) {
        Object obj = codeTableCache.getCacheByTableName(tableName);
        return new BaseResult(obj);
    }

    @Override
    public BaseResult getAllCodeTables() {
        Map<Object, Object> map = codeTableCache.getAllCodeTableCache();
        return new BaseResult(map);
    }

    @Override
    public BaseResult getallcodetableskv() {
        Map<Object, Object> map = codeTableCache.getallcodetableskv();
        return new BaseResult(map);
    }
}
